package com.bxd.baodan.fragment;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.MsgActivity;
import com.bxd.baodan.adapter.PlanerMsgAdapter;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.widget.MyListView;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMFriendFutureItem;
import com.tencent.TIMGroupCacheInfo;
import com.tencent.TIMMessage;
import com.tencent.qcloud.presentation.presenter.FriendshipManagerPresenter;
import com.tencent.qcloud.presentation.viewfeatures.ConversationView;
import com.tencent.qcloud.presentation.viewfeatures.FriendshipMessageView;
import com.tencent.qcloud.timchat.model.Conversation;
import com.tencent.qcloud.timchat.model.ConversationPresenter;
import com.tencent.qcloud.timchat.model.FriendshipConversation;
import com.tencent.qcloud.timchat.model.MessageFactory;
import com.tencent.qcloud.timchat.model.NomalConversation;
import com.tencent.qcloud.timchat.utils.PushUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


/**
 * 会话列表界面
 */
public class MsgPlanerFragment extends BaseFragment implements ConversationView, FriendshipMessageView {

    Dao<MessageItem, ?> dao;
    private View view;
    private List<Conversation> conversationList = new LinkedList<>();
    private PlanerMsgAdapter adapter;
    private MyListView planerLv;
    private ConversationPresenter presenter;
    private FriendshipManagerPresenter friendshipManagerPresenter;
    private List<String> groupList;
    private FriendshipConversation friendshipConversation;
    boolean isPrepared = false;
    View emptyView;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_planer_msg, container, false);
            planerLv = (MyListView) view.findViewById(R.id.list_planer);
            emptyView = view.findViewById(R.id.empty_view);
            try {
                dao = DBHelper.getInstance(context).getDao(MessageItem.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            // TODO: 17/7/22 这个view是自己绘制的
            adapter = new PlanerMsgAdapter(getActivity(), R.layout.planer_msg_item, conversationList);
            planerLv.setAdapter(adapter);

            friendshipManagerPresenter = new FriendshipManagerPresenter(this);
            presenter = new ConversationPresenter(this);
            presenter.getPlanerConversation();
            registerForContextMenu(planerLv);

        }
        notifyChanged();
        refresh();
        return view;

    }




    public void reloadData() {
        //判断是切换账户后第一次resume

        if (presenter != null) {
            presenter.getPlanerConversation();
        }
    }


    /**
     * 初始化界面或刷新界面
     *
     * @param conversationList
     */
    @Override
    public void initView(List<TIMConversation> conversationList) {
        this.conversationList.clear();
        groupList = new ArrayList<>();
        for (TIMConversation item : conversationList) {
            switch (item.getType()) {
                case C2C:
                case Group:
                    this.conversationList.add(new NomalConversation(item));
                    groupList.add(item.getPeer());
                    break;
            }
        }
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 更新最新消息显示
     *
     * @param message 最后一条消息
     */
    @Override
    public void updateMessage(TIMMessage message) {
        if (message == null) {
            notifyChanged();
            return;
        }
        if (message.getConversation().getType() == TIMConversationType.System) {
            return;
        }
        NomalConversation conversation = new NomalConversation(message.getConversation());
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation c = iterator.next();
            if (conversation.equals(c)) {
                conversation = (NomalConversation) c;
                iterator.remove();
                break;
            }
        }
        conversation.setLastMessage(MessageFactory.getMessage(message));
        conversationList.add(conversation);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 更新好友关系链消息
     */
    @Override
    public void updateFriendshipMessage() {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }

    /**
     * 删除会话
     *
     * @param identify
     */
    @Override
    public void removeConversation(String identify) {
        Iterator<Conversation> iterator = conversationList.iterator();
        while (iterator.hasNext()) {
            Conversation conversation = iterator.next();
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(identify)) {
                iterator.remove();
                notifyChanged();
                return;
            }
        }
    }

    /**
     * 更新群信息
     *
     * @param info
     */
    @Override
    public void updateGroupInfo(TIMGroupCacheInfo info) {
        for (Conversation conversation : conversationList) {
            if (conversation.getIdentify() != null && conversation.getIdentify().equals(info.getGroupInfo().getGroupId())) {
                notifyChanged();
                return;
            }
        }
    }

    /**
     * 刷新
     */


    public void setRedIcon() {
        long conUnread = 0;
        for (Conversation con :
                conversationList) {
            long count = con.getUnreadNum();
            conUnread = count++;
        }
        boolean haveUnread = conUnread  > 0;
            ((MsgActivity) context).setPlanerRed(haveUnread);
    }

    @Override
    public void refresh() {
      //  setRedIcon();
        // TODO: 2017/4/5 添加提问
        // &&
        if (LoginInfo.getInstance(App.getContext()).isLogin() && conversationList.size() != 0) {
            emptyView.setVisibility(View.GONE);
            planerLv.setVisibility(View.VISIBLE);
            Collections.sort(conversationList);

        } else {
            conversationList.clear();
            emptyView.setVisibility(View.VISIBLE);
            // TODO: 17/7/23 显示顾问列表
            planerLv.setVisibility(View.GONE);

        }

        notifyChanged();
        // TODO: 17/7/29 send 广播


    }


    /**
     * 获取好友关系链管理系统最后一条消息的回调
     *
     * @param message     最后一条消息
     * @param unreadCount 未读数
     */
    @Override
    public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {
        if (friendshipConversation == null) {
            friendshipConversation = new FriendshipConversation(message);
            conversationList.add(friendshipConversation);
        } else {
            friendshipConversation.setLastMessage(message);
        }
        friendshipConversation.setUnreadCount(unreadCount);
        Collections.sort(conversationList);
        refresh();
    }

    /**
     * 获取好友关系链管理最后一条系统消息的回调
     *
     * @param message 消息列表
     */
    @Override
    public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {
        friendshipManagerPresenter.getFriendshipLastMessage();
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Conversation conversation = conversationList.get(info.position);
        if (conversation instanceof NomalConversation) {
            menu.add(0, 1, Menu.NONE, getString(R.string.conversation_del));
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        NomalConversation conversation = (NomalConversation) conversationList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                if (conversation != null) {
                    if (presenter.delConversation(conversation.getType(), conversation.getIdentify())) {
                        conversationList.remove(conversation);
                        notifyChanged();
                    }
                }
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    public void notifyChanged() {
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isPrepared = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isPrepared && getUserVisibleHint()) {
            refresh();
            PushUtil.getInstance().reset();
        }
        reloadData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

//        if (!hidden) {
//
//            if (!hidden) {
//                reloadData();
//                refresh();
//            }
//        }
//

    }


}
